package cmds

import (
	"fmt"
	"generate-iot-cmd/internal/model"
	"os"
)

type CMDService struct {
	IOTCmdModel model.CmdModel
	Commands    []string
}

func (c *CMDService) NewIOTCmd(addressIdx []string, address map[string][]string, interval int, maxCount int, sn string) {
	c.IOTCmdModel.AddressModel = make([]model.AddressModel, 0)

	for _, v := range addressIdx {
		addressModel := model.AddressModel{
			Address: v,
			Cmds:    address[v],
		}
		c.IOTCmdModel.AddressModel = append(c.IOTCmdModel.AddressModel, addressModel)
	}
	c.IOTCmdModel.Interval = interval
	c.IOTCmdModel.MaxCount = maxCount
	c.IOTCmdModel.SN = sn

}

func (c *CMDService) GetCmdFileContent() string {

	c.Commands = initCmds(c.IOTCmdModel)

	cmds := generateCmds(c)

	reveiver := generateUartReceiver(c)

	sendCmds := generateSendCmds(c)

	fileContent := cmds + reveiver + sendCmds
	return fileContent
}

func (c *CMDService) GenerateCmdTxT(fileContent string) error {
	fileName := fmt.Sprintf("%s.txt", c.IOTCmdModel.SN)
	// 覆盖写入（权限默认 0666）
	err := os.WriteFile(fileName, []byte(fileContent), 0666)
	if err != nil {
		return err
	}
	return nil
}
